package controller.login;


import core.util.ValidationUtil;
import domain.entity.UserInfos;
import domain.entity.base.UserInfo;
import domain.service.user.UserInfosService;
import domain.service.user.UserWatchLoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import util.WebContextUtil;

/**
 * Created by bowen on 2016/7/28.
 */
@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserWatchLoginService userWatchLoginService;

    /**
     * 跳转到问卷列表
     *
     * @return
     * @author songbaoming
     * @date 2017年5月21日
     */
    @RequestMapping(value = "initPage", method = RequestMethod.GET)
    public String initPage(Model model, String code) throws Exception {
        String ur = "";
        UserInfo userInfo = ValidationUtil.getUserInfo(code);
        if (userInfo != null) {
            logger.info(userInfo.getHeadimgurl() + "++++++++++initPage+++++++++++++++");
            logger.info(userInfo.getNickname() + "++++++++++nickname+++++++++++++++");
            Long cou = userWatchLoginService.getUserWatchCou(userInfo.getOpenid());
            if (cou > 0) {
                ur = "home";
                model.addAttribute("headimgurl", userInfo.getHeadimgurl());
                model.addAttribute("nickname", userInfo.getNickname());
            } else {
                ur = "login";
                model.addAttribute("openid", userInfo.getOpenid());
            }
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            if (userInfo != null) {
                session.setAttribute("user",userInfo);
            }
        }
        return ur;
    }

    @RequestMapping(value = "/home")
    public String mapResources(Model model) {
        UserInfo userInfo = WebContextUtil.getCurrentUser();
        model.addAttribute("headimgurl", userInfo.getHeadimgurl());
        model.addAttribute("nickname", userInfo.getNickname());
        return "home";
    }

}
